package net.siufung.market.base.tenant.controller.regulation;

import lombok.AllArgsConstructor;
import net.siufung.core.exception.BizServiceException;
import net.siufung.core.model.VerifyRepeatDto;
import net.siufung.core.model.enums.MethodEventEnum;
import net.siufung.core.model.regulation.AbstractRegulation;
import net.siufung.market.base.tenant.mapper.entity.TenantQuota;
import net.siufung.market.base.tenant.service.ITenantQuotaService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 陈建峰
 * @since 2022/6/28 1:58 下午
 */
@AllArgsConstructor
public class TenantQuotaCreateBatchRegulation extends AbstractRegulation<List<TenantQuota>> {

    private static final long serialVersionUID = -2593040879568686019L;

    private final ITenantQuotaService tenantQuotaService;

    @Override
    public boolean isSatisfiedBy(List<TenantQuota> tenantQuotaList) {
        if(!checkRepeatQuotaKey(tenantQuotaList)){
            throw new BizServiceException("参数中租户配额Key不能重复！");
        }
        for (TenantQuota tenantQuota: tenantQuotaList) {
            VerifyRepeatDto<Integer> verifyRepeatDto = new VerifyRepeatDto<>();
            verifyRepeatDto.setMethodEventEnum(MethodEventEnum.ADD);
            verifyRepeatDto.setPk(null);
            verifyRepeatDto.setVerifyKeyValue(tenantQuota.getQuotaKey());
            verifyRepeatDto.setTenantId(String.valueOf(tenantQuota.getTenantId()));
            if(!tenantQuotaService.checkTenantQuotaKeyNotRepeat(verifyRepeatDto)){
                throw new BizServiceException("租户配额Key不能与现有租户配额Key重复！");
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 验证是否重复
     * @return Boolean
     */
    private Boolean checkRepeatQuotaKey(List<TenantQuota> tenantQuotaList) {
        return tenantQuotaList.size() != (tenantQuotaList.stream().map(TenantQuota::getQuotaKey)
                .collect(Collectors.toList()).stream().distinct().count());
    }

}
